package com.xiongwei.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Writer定义了所有字符输出流的超类:
 *      FileWriter定义了文件字符流输出
 *      CharArrayWriter和StringWriter在内存中模拟一个字符流输出
 *
 * 使用try(resource)保证Writer正确关闭
 *
 * Writer是基于OutputStream构造的,可通过OutputStreamWriter将OutputStream转换为Writer,转换时需要制定编码
 * @author XiongWei
 * @date 2021/1/11
 */
public class WriterUse {

    public static void main(String[] args) {
        WriterUse wu = new WriterUse();
        wu.testFileWriter();
        wu.testCharArrayWriter();
    }

    public void testFileWriter() {
        try (Writer writer = new FileWriter("src/com/xiongwei/io/writeme.txt",StandardCharsets.UTF_8)) {
            writer.write("write me.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void testCharArrayWriter() {
        try (CharArrayWriter caw = new CharArrayWriter()) {
            caw.write(65);
            caw.write(66);
            caw.write("xxx");
            char[] chars = caw.toCharArray();
            System.out.println(chars);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void testOutputSreamWriter() {
        try (Writer writer = new OutputStreamWriter(new FileOutputStream("readme.txt"), "UTF-8")) {
            // TODO:
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
